package com.farm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.farm.entity.User;
import com.farm.service.UserService;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String registerPage() {
        return "auth/register";
    }

    @PostMapping("/register")
    public String register(User user, @RequestParam("role") String role, RedirectAttributes redirectAttributes) {
        try {
            user.setRole(role);
            userService.register(user);
            redirectAttributes.addFlashAttribute("message", "注册成功，请等待管理员审核");
            return "redirect:/login";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "注册失败：" + e.getMessage());
            return "redirect:/register";
        }
    }

    @GetMapping("/")
    public String home() {
        return "login";
    }
} 